package com.tyj.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tyj.common.exception.BizCodeEnume;
import com.tyj.common.utils.HttpUtils;
import com.tyj.common.utils.R;
import com.tyj.gulimall.member.excepiton.PhoneExistException;
import com.tyj.gulimall.member.excepiton.RigsterUserException;
import com.tyj.gulimall.member.excepiton.UserNameExistException;
import com.tyj.gulimall.member.service.MemberLevelService;
import com.tyj.gulimall.member.vo.SocialUser;
import com.tyj.gulimall.member.vo.UserLoginVo;
import com.tyj.gulimall.member.vo.UserRegistVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyj.common.utils.PageUtils;
import com.tyj.common.utils.Query;

import com.tyj.gulimall.member.dao.MemberDao;
import com.tyj.gulimall.member.entity.MemberEntity;
import com.tyj.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService levelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(UserRegistVo vo) throws RuntimeException {
        //效验手机是否存在
        List<MemberEntity> entitie1 = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if (entitie1.size() != 0) {
            //说明手机号已经存在抛出异常
            throw new PhoneExistException();
        }

        //效验邮箱是否存在
        List<MemberEntity> entitie2 = baseMapper.selectList(new QueryWrapper<MemberEntity>().eq("username", vo.getUserName()));
        if (entitie2.size() != 0) {
            //说明手机号已经存在抛出异常
            throw new UserNameExistException();
        }

        //上面若没有抛异常则效验成功  设置参数存入数据库
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(vo.getUserName());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);         //密码加盐
        Long memberDefaultLeverId = levelService.queryDefault();   //查询数据库 默认等级id
        memberEntity.setLevelId(memberDefaultLeverId);
        memberEntity.setMobile(vo.getPhone());

        int insert = this.baseMapper.insert(memberEntity);
        if (insert != 1) {
            throw new RigsterUserException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getAccount()).or().eq("mobile", vo.getAccount()));
        //得到密码进行加密效验
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (memberEntity != null) {
            String password = memberEntity.getPassword();
            boolean result = passwordEncoder.matches(vo.getPassword(), password);
            if (result) {
                //密码效验正确返回此对象
                return memberEntity;
            } else {
                //效验失败返回null
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登录与注册合并逻辑
        String uid = socialUser.getUid();
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //这个用户注册过 更新令牌与过期时间
            MemberEntity memberEntity1 = new MemberEntity();
            memberEntity1.setId(memberEntity.getId());
            memberEntity1.setAccessToken(socialUser.getAccess_token());
            memberEntity1.setExpireIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity1);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpireIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //没有查到当前社交用户 需要注册一个
            MemberEntity regist = new MemberEntity();
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //名称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    //...
                    regist.setUsername(name);
                    regist.setGender("m".equals(gender)?1:0);
                    regist.setAccessToken(socialUser.getAccess_token());
                    regist.setExpireIn(socialUser.getExpires_in());
                    regist.setSocialUid(socialUser.getUid());
                    baseMapper.insert(regist);
                    return regist;
                }else {
                    log.error("远程获取社交用户信息失败");
                    return null;
                }
        }
    }


}